<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import UploadFile from '@/components/uploadFile.vue'
import api from '@/api'
import { Message } from '@arco-design/web-vue'
import { transformDuration } from '@/utils'
import useAuthStore from '@/store/auth'

const authStore = useAuthStore()
const $route = useRoute()
const $router = useRouter()
const order_no = ref('')
const defaultCategory = ref('')
const pageVal = ref(1)
const pageSize = ref(10)
const listTotal = ref(0)
const listData = ref()
const formVisible = ref(false)
const formData = ref({
  id: null,
  order_type: 1,
  order_file: '',
  order_content: '',
  contacts: [
    {
      name: authStore.name,
      mobile: authStore.username,
    },
  ],
})

const getListData = async (page) => {
  try {
    const res = await api.get('course/customizedOrderList', {
      params: {
        order_no: order_no.value,
        page,
        pageSize: pageSize.value,
      },
    })
    console.log('res', res)
    listData.value = res.data.items
    listTotal.value = res.data.pageInfo.total
    pageVal.value = page
  } catch (error) {
    console.error(error)
  }
}

const changeFile = async (e) => {
  console.warn('e', e)
  formData.value.order_file = e
}

const showFormData = async (record) => {
  if (record) {
    formData.value.id = record.id
    switch (record.order_type * 1) {
      case 1:
        formData.value.order_type_text = '课程定制'
        break
    }
    formData.value.order_file = record.order_file
    formData.value.order_content = record.order_content
    formData.value.contacts = JSON.parse(record.contacts)
  } else {
    resetFormData()
  }
  formVisible.value = true
}

const resetFormData = async () => {
  formData.value = {
    id: null,
    order_type: 1,
    order_file: '',
    order_content: '',
    contacts: [
      {
        name: authStore.name,
        mobile: authStore.username,
      },
    ],
  }
}

const addContacts = async () => {
  formData.value.contacts.push({
    name: '',
    mobile: '',
  })
}

const deleteContacts = async (index) => {
  formData.value.contacts.splice(index, 1)
}

const formSubmit = async () => {
  console.log('formData', formData.value)
  var obj = { ...formData.value }
  var val = 0
  for (const item of obj.contacts) {
    if (!item.name || !item.mobile) {
      val++
    }
  }
  if (val) {
    Message.error('联系人信息有误，请检查')
    return false
  }
  obj.contacts = JSON.stringify(obj.contacts)
  try {
    const res = await api.post('course/customizedOrder', obj)
    Message.success(res.message)
    formVisible.value = false
    getListData(1)
    resetFormData()
  } catch (error) {
    console.error('error', error)
    return false
  }
}

const deleteItem = async (id) => {
  try {
    const res = await api.get('course/del/' + id)
    Message.success(res.message)
    getListData(1)
  } catch (error) {
    console.error('error', error)
    return false
  }
}

const handlePay = async (order_no) => {
  try {
    const res = await api.get('course/payCustomizedCourse', {
      params: {
        order: order_no,
      },
    })
    Message.success(res.message)
    getListData(1)
  } catch (error) {
    console.error('error', error)
    return false
  }
}

// const handlePay = async (id) => {
//   try {
//     const res = await api.get('course/createCourseOrder/' + id)

//   } catch (error) {
//     console.error('error', error)
//     return false
//   }
// }

getListData(1)
</script>

<template>
  <div class="page">
    <div class="header">
      <a-space>

        <a-input :style="{ width: '240px' }"
                 v-model="order_no"
                 placeholder="按订单编号查询"
                 allow-clear />

        <a-button @click="getListData(1)"
                  type="primary">查询</a-button>

      </a-space>

      <a-button @click="showFormData()"
                type="primary">发起订单</a-button>
    </div>

    <a-table :data="listData"
             @page-change="getListData"
             :pagination="{
              showTotal: true,
              size: 'small',
              total: listTotal,
              pageSize: pageSize,
              current: pageVal,
            }">
      <template #columns>
        <a-table-column title="序号"
                        :width="60">
          <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
        </a-table-column>
        <a-table-column title="订单编号"
                        data-index="order_no"></a-table-column>
        <a-table-column title="订单类型">
          <template #cell="{ record }">
            <div v-if="record.order_type==1">课程定制</div>
          </template>
        </a-table-column>
        <a-table-column title="订单时间"
                        data-index="created_at"></a-table-column>
        <a-table-column title="订单状态">
          <template #cell="{ record }">
            <div v-if="record.order_status==0">等待发起</div>
            <div v-if="record.order_status==1">待支付</div>
            <div v-if="record.order_status==2">已支付</div>
          </template>
        </a-table-column>
        <a-table-column title="订单价格"
                        data-index="order_price"></a-table-column>
        <a-table-column title="操作"
                        align="right"
                        :width="300">
          <template #cell="{ record }">
            <a-space>
              <a-button v-if="record.order_status==1"
                        @click="handlePay(record.order_no)"
                        type="outline"
                        size="mini">支付</a-button>
              <a-button @click="showFormData(record)"
                        type="primary"
                        size="mini">查看详情</a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <a-modal :title="formData.id ? '订单详情' : '创建订单'"
             width="600px"
             :footer="!formData.id"
             okText="提交"
             :on-before-ok="formSubmit"
             v-model:visible="formVisible">
      <a-form>
        <a-form-item label="订单类型">
          <a-select v-if="!formData.id"
                    :style="{width:'400px'}"
                    :default-value="formData.order_type"
                    placeholder="请选择订单类型">
            <a-option :value="1">课程定制</a-option>
          </a-select>
          <a-input v-else
                   :readonly="formData.id"
                   :style="{width:'400px'}"
                   v-model="formData.order_type_text"
                   placeholder="请输入章节标题"
                   allow-clear></a-input>
        </a-form-item>
        <a-form-item label="上传文件">
          <UploadFile v-if="!formData.id"
                      dir="plans/biographical_notes"
                      :maxSize="1"
                      @change="changeFile"
                      :accepts="[
              '.doc',
              '.docx',
              '.pdf',
              'image/*',
              'image/jpeg',
              'image/png',
              'image/jpg',
              'application/pdf',
              'application/msword',
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            ]" />
          <a-link v-if="formData.order_file"
                  :href="formData.order_file"
                  icon>文件地址</a-link>
        </a-form-item>
        <a-form-item label="订单需求">
          <a-textarea :readonly="formData.id"
                      :style="{width:'400px'}"
                      v-model="formData.order_content"
                      placeholder="请输入订单需求"
                      auto-size />
        </a-form-item>
        <a-form-item label="联系人">
          <div v-if="!formData.id"
               class="flex fd_c">
            <div v-for="(item,index) in formData.contacts"
                 :key="index"
                 class="mb10 flex at_c">
              <a-input-group class="mr10">
                <a-input v-model="item.name"
                         :style="{width:'180px'}"
                         placeholder="请输入联系人姓名" />
                <a-input v-model="item.mobile"
                         :style="{width:'180px'}"
                         placeholder="请输入联系人电话" />
              </a-input-group>
              <icon-plus-circle-fill v-if="!index"
                                     @click="addContacts"
                                     class="can"
                                     size="30"
                                     style="color: #124acc;" />
              <icon-minus-circle-fill v-else
                                      @click="deleteContacts(index)"
                                      class="can"
                                      size="30"
                                      style="color: red;" />
            </div>
          </div>
          <div v-else
               class="flex fd_c">
            <div v-for="(item,index) in formData.contacts"
                 :key="index"
                 class="mb10 flex at_c">
              <a-input-group class="mr10">
                <a-input readonly
                         v-model="item.name"
                         :style="{width:'200px'}"
                         placeholder="请输入联系人姓名" />
                <a-input readonly
                         v-model="item.mobile"
                         :style="{width:'200px'}"
                         placeholder="请输入联系人电话" />
              </a-input-group>
            </div>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

  </div>
</template>

<style scoped>
.page {
  height: 100%;
}

.header {
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>